package com.sxp.servlet;

import com.sxp.dao.UserDao;
import com.sxp.dao.impl.UserDaoImpl;
import com.sxp.util.EncryptUtils;
import com.sxp.bean.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author 宋晓盼
 * @since 2019/6/5 10:20
 */
@WebServlet("/register")
public class RegisterServlet extends HttpServlet {

    @Override
    protected  void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String repassword = req.getParameter("repassword");

        HttpSession session = req.getSession();

        // 判断用户输入的信息是否有空
        if (username != null && password != null && repassword != null) {

            UserDao userDao = new UserDaoImpl();

            if (userDao.getByUsername(username) != null) {
                session.setAttribute("msg", "用户名已存在！");
                resp.sendRedirect("/obs/message.jsp");
            }

            if (password.equals(repassword)) {
                User user = new User(username, EncryptUtils.md5(password));

                Integer userId = userDao.save(user);
                // 判断是否成功插入用户数据
                if (userId != null) {
                    session.setAttribute("msg", "注册成功！");
                    resp.sendRedirect("/obs/message.jsp");
                } else {
                    session.setAttribute("msg", "注册失败！");
                    resp.sendRedirect("/obs/message.jsp");
                }
            } else {
                session.setAttribute("msg", "注册失败！");
                resp.sendRedirect("/obs/view/message.jsp");
            }
        } else {
            session.setAttribute("msg", "注册信息不能有空！");
            resp.sendRedirect("/obs/view/message.jsp");
        }


    }
}
